package com.gt.ao.utils;

import sun.misc.BASE64Encoder;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.TreeMap;
import java.util.jar.JarFile;
import java.util.regex.Pattern;

/**
 * @author gt.ao
 * @description //TODO
 * @createTime  2022/7/11 15:59
 **/
public class TextSplitUtil {

    private static String testPath = "/Users/gt.ao/Desktop/txqr.txt";

    private static int bufferSize = 800;


    /**
     * 拆分成文件
     **/
    public static String[] splitFile(String filePath,boolean deleteTmpFile,String name) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        FileChannel inputChannel = fis.getChannel();
        final long fileSize = inputChannel.size();
        double d = file.length()*1.0/bufferSize;
        int fileCount = Double.valueOf(Math.ceil(d)).intValue();
        String[] result = new String[fileCount];
        long startPosition = 0; //子文件开始位置
        long endPosition = 0;
        for (int i = 0; i < fileCount; i++) {
            if (i + 1 != fileCount) {
                endPosition += bufferSize;
            }else{
                endPosition = fileSize; //最后一个文件直接指向文件末尾
            }
            File curFn = File.createTempFile("Base64TextSplitFile","");
            System.out.println("文件拆分----->"+curFn.getAbsolutePath());
            if(deleteTmpFile){
                curFn.deleteOnExit();
            }
            FileOutputStream fos = new FileOutputStream(curFn);
            FileChannel outputChannel = fos.getChannel();
            inputChannel.transferTo(startPosition, endPosition - startPosition, outputChannel);//通道传输文件数据
            byte[] tb = (i+"|"+fileCount+"|"+name+",").getBytes();
            ByteBuffer byteBuffer = ByteBuffer.wrap(tb);
            outputChannel.write(byteBuffer,0);
            outputChannel.close();
            fos.close();
            startPosition = endPosition;
            result[i] = curFn.getAbsolutePath();
        }
        inputChannel.close();
        fis.close();
        return result;
    }

    /**
     * 拆分到内存，返回拆分后的文件内存数组
     **/
    public static TreeMap<Integer, String> splitFileMem(String filePath) throws IOException {
        String args = System.getProperty("buffer");
        if(args!=null){
            bufferSize = Integer.parseInt(args);
        }
        System.out.println("二维码容量值："+bufferSize);
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        FileChannel inputChannel = fis.getChannel();
        double d = file.length()*1.0/bufferSize;
        int fileCount = Double.valueOf(Math.ceil(d)).intValue();
        System.out.println("拆分出文件总数："+fileCount);
        ByteBuffer bf = ByteBuffer.allocate(bufferSize);
        //java.util.List<String> result = new ArrayList<>(fileCount);
        TreeMap<Integer,String> treeMap = new TreeMap<>();
        int fcAddHomePage = fileCount+1;
        BASE64Encoder base64Encoder = new BASE64Encoder();
        for (int i = 1; i <= fileCount; i++) {
            inputChannel.read(bf);
            String t1 = "yr://"+i+"|"+fcAddHomePage+"|"+bf.position()+",";
            byte[] tb = new byte[bf.position()];
            bf.flip();
            bf.get(tb,0,tb.length);
            treeMap.put(i,t1+base64Encoder.encode(tb));
            bf.clear();
        }
        inputChannel.close();
        fis.close();
        return treeMap;
    }

    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        File file = new File(testPath);
        double d = file.length()*1.0/bufferSize;
        splitFile(testPath,true,"");
        long endTime = System.currentTimeMillis();
        System.out.println("耗费时间： " + (endTime - startTime) + " ms");
    }

    private static int getJarFileNameArgs() {
        try{
            String jarName = System.getProperty("java.class.path");
            if(jarName.indexOf("Txqr")!=-1&&jarName.indexOf("-")!=-1){
                String val = jarName.split("\\.")[0].split("-")[1];
                if(isNumber(val)){
                    return Integer.parseInt(val);
                }else{
                    return 0;
                }

            }
        }catch(Exception e){}
        return 0;
    }

    public static boolean isNumber(String string) {
        if (string == null){
            return false;
        }
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(string).matches();
    }

}
